#ifndef __UTILS__LOAD_REGION__
#define __UTILS__LOAD_REGION__

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include "../include/Region.hpp"

//extern int degree_of_basis_function;

Region load_region(std::string shape)
{
    std::cerr << "loading quadrature points from " << shape <<".quad" << std::endl;
    std::vector<Node> refnodes;
    
    if(shape == "triangle")
    {
        std::ifstream fin("../data/triangle.quad");
        int refd = 5;
        int num_table;
        fin >> num_table;
        //std::cout << num_table << std::endl;
        int degree, accuracy;
        double trash;
        for(int d=0; d<refd-1; d++)
        {
            fin >> degree >> accuracy;
            for(int p=0; p<accuracy; p++)
            {
                fin >> trash >> trash >> trash;
            }
        }
    
        double x, y, w;
        fin >> degree >> accuracy;
        for(int p=0; p<accuracy; p++)
        {
            fin >> x >> y >> w;
            Node n({x,y}, w);
            refnodes.push_back(n);
        }
        fin.close();
        std::cerr << "finish reading triangle quadrature points" << std::endl;
    }

    else if(shape == "square")
    {
        std::ifstream fin("../data/square.quad");
        std::cerr << "reading data for square quadrature" << std::endl;
        int refd = 9;
        double trash = 0.0;
        bool flag = 1; 
        while (flag)
        {
//            std::cerr << "enter loop" << std::endl;
            int degree = 0;
            double trash = 0.0;
            fin >> degree;
            if(degree == refd)
            {
                double x = 0.0;
                double y = 0.0;
                double w = 0.0;
                for(int i=0; i<degree; i++)
                {
                    fin >> x >> y >> w;
                    Node n({x,y}, w);
                    std::cout << n;
                    refnodes.push_back(n);
                }
                flag = 0;
//                std::cerr << "break the loop" << std::endl;
                break;
            }
            else
            {
                for(int i=0; i<degree; i++)
                {
                    fin >> trash >> trash >> trash;
                }
            }
        }
        std::cerr << "finish reading square quadrature points" << std::endl;
        fin.close();
    }
    else
    {
        std::cerr << "please choose legal quadrature area(triangle or square)" << std::endl;
        abort();
    }
    
    Region ref(refnodes);
    return ref;
}

#endif
